package cn.emall.controller;

import cn.emall.config.JwtProperties;
import cn.emall.pojo.Product;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import cn.emall.service.ProductService;
import utils.ImageUploadUtil;
import utils.ResponseBean;
import utils.ResultCode;

import java.io.File;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Allen_HJL
 * @version 1.0
 * @date 2020/9/13 11:18
 */
@RestController
@RequestMapping("/product")
@Api(value = "产品接口")
public class ProductController {
    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private ProductService productService;


    @GetMapping("/getAllProducts")
    @ApiOperation(value = "获得所有产品信息（包含删除的）", notes = "直接获得")
    public ResponseBean getAllProducts(){
        System.out.println("getAllProducts！！！");
        return ResponseBean.success(ResultCode.FIND_MANYDATA_SUCCESS,productService.list());
    }

    @GetMapping("/getAllActiveProducts")
    @ApiOperation(value = "获得所有产品信息（不含删除的）", notes = "直接获得")
    public ResponseBean getAllActiveProducts(){
        System.out.println("getAllActiveProducts");
        List<Product> productList = productService.list();
        List<Product> activeList = new ArrayList<>();
        int length = productList.size();
        for (int i = 0; i < length; i++) {
            Product product = productList.get(i);
            if(product.getStatus() != 3){
                activeList.add(product);
            }
        }
        return ResponseBean.success(ResultCode.FIND_MANYDATA_SUCCESS, activeList);
    }

    @GetMapping("/getOneProductById/{productId}")
    @ApiOperation(value = "productId获得一件产品信息", notes = "直接获得")
    public ResponseBean getAllActiveProducts(@PathVariable int productId){

        System.out.println("getOneProduct/{productId}");
        Product product = productService.getById(productId);

        return ResponseBean.success(ResultCode.FIND_DATA_SUCCESS, product);
    }

    @GetMapping("/getProductsByName/{name}")
    @ApiOperation(value = "productName获得产品信息", notes = "直接获得")
    public ResponseBean getAllActiveProducts(@PathVariable String name){
        System.out.println("getOneProduct/{name}");
        List<Product> products = productService.list(new QueryWrapper<Product>().eq("name", name));
        return ResponseBean.success(ResultCode.FIND_DATA_SUCCESS, products);
    }

    @GetMapping("/getProductsByPage/{pageCurrent}/{pageSize}")
    @ApiOperation(value = "分页获得产品信息", notes = "直接获得")
    public ResponseBean getAllActiveProducts(@PathVariable int pageCurrent, @PathVariable int pageSize){
        IPage<Product> page = productService.page(new Page<>(pageCurrent, pageSize));
        List<Product> products = page.getRecords();
        Map<String, Object> map = new HashMap<>();
        map.put("total", page.getPages());
        map.put("current", page.getCurrent());
        for(Product product : products){
            int i = 1;
            product.setAdditionalData("lalalalalaAdditionalData" + i);  //如果分页查询要查询别的表的字段信息，可以在这里加入
            i++;
        }
        map.put("productList", products);
        return ResponseBean.success(ResultCode.FIND_MANYDATA_SUCCESS, map);

//        IPage<Map<String, Object>> mapIPage = productService.pageMaps(new Page<>(pageCurrent, pageSize));
//        System.out.println(mapIPage.getRecords());
//        List<Map<String, Object>> list = mapIPage.getRecords();
//        for(int i=0; i<list.size(); i++){
//
//        }
//        List<Map<String, Object>> lastList = new ArrayList<>();
//        String lala = "lalala";
//        Map<String, Object> additionalData = new HashMap<>();
//        additionalData.put("What happend?", lala);
//        lastList.add(additionalData);
//        mapIPage.getRecords().add(new HashMap<String, Object>().put("What happend?", lala));
//        mapIPage.condition().put("What happend?", lala);
//        mapIPage.getRecords().add(additionalData);  //在records链表里加入额外
        //对mapIPage进行getRecords方法得到原始Product数据，接着调用别的模块对应的表中 需要展示在分页页面上的字段 的方法，
        //并提前将这些字段加进pojo里的ProjectPro里面

//        return ResponseBean.success(ResultCode.FIND_MANYDATA_SUCCESS, mapIPage);

    }

    /*
    @RequestMapping("/addProduct")
    public ResponseBean addProduct(int category_id, String name, String subtitle,
                                   String mainImage, String subImages, String detail,
                                   double price, int stock, int status){
        //根据类别id查找类别表

        //库存不能为0，价格不能小于0，状态默认为1（在售）

        //以上均符合则往下执行
        System.out.println(1111);
        Product product = new Product(category_id, name,subtitle,
                mainImage, subImages, detail, price, stock, status);
        boolean save = productService.save(product);
        if(save == true) {
            System.out.println("success");
            return ResponseBean.success(ResultCode.ADD_DATA_SUCCESS,productService.list());
        }else{
            return ResponseBean.failure(ResultCode.ADD_DATA_FAILURE, "error");
        }
    }
     */

    @GetMapping("/upLoadImage/{Image}")
    public ResponseBean upLoadImage(@PathVariable File Image){
        String newImageName = Image.toString() + new Date();
        try {
            ImageUploadUtil.uploadImage("hhh", Image, newImageName);
            return ResponseBean.success(ResultCode.ADD_DATA_SUCCESS, newImageName);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        return ResponseBean.failure(ResultCode.ADD_DATA_FAILURE, "上传失败");
    }

    @PostMapping("/addProduct")
    public ResponseBean addProduct(@RequestBody Product product){
        //根据类别id查找类别表
        //前端通过下拉框触发搜索商品类别id的方法

        //库存不能为0，价格不能小于0，状态默认为1（在售）
        //即前端在新增商品时，默认状态为 在售， 不可更改
        //前端也可以在库存以及价格两个框进行相关js判断
        if(product.getStock() <= 0 || product.getPrice() <= 0){
            return ResponseBean.failure(ResultCode.ADD_DATA_FAILURE, "error 库存不能为0，价格不能小于0");
        }

//        String mainImage = product.getMainImage();
//        ImageUploadUtil.uploadImage("hhh", new );
//
        //以上均符合则往下执行
        System.out.println("/addProduct");
        boolean save = productService.save(product);
        if(save == true) {
            System.out.println("success");
            return ResponseBean.success(ResultCode.ADD_DATA_SUCCESS,productService.list());
        }else{
            return ResponseBean.failure(ResultCode.ADD_DATA_FAILURE, "error");
        }
    }

    @GetMapping("/deleteProduct/{productId}")
    public ResponseBean deleteProduct(@PathVariable int productId){
        //在界面上看到的商品只能为在售或下架的商品，删除的商品不可见

        //先查看该商品状态信息 如果为下架，则可以删除，如果在售则给出相应提示
        System.out.println("/deleteProduct/{productId}");
        Product product = productService.getById(productId);
        if(product.getStatus() == 1){
            System.out.println("商品在售，不可直接删除");
            return ResponseBean.failure(ResultCode.DELETE_DATA_FAILURE);
        }else { //status == 2
            product.setStatus(3);
            return ResponseBean.success(ResultCode.DELETE_DATA_SUCCESS);
        }

    }

    //整个修改
    @PostMapping("/updateProduct")
    public ResponseBean updateProduct(@RequestBody Product product){

        product.setUpdateTime(new Date());
        boolean b = productService.updateById(product);
        if(b == true){
            return ResponseBean.success(ResultCode.UPDATE_DATA_SUCCESS);
        }else{
            return ResponseBean.failure(ResultCode.UPDATE_DATA_FAILURE);
        }

    }

    //根据id、stock修改stock
    @GetMapping("/updateProduct/{id}/{quantity}")
    public ResponseBean updateProduct(@PathVariable int id, @PathVariable int quantity){

        Product product = productService.getById(id);
        product.setUpdateTime(new Date());
        product.setStock(product.getStock()-quantity);
        boolean b = productService.updateById(product);
        if(b == true){
            return ResponseBean.success(ResultCode.UPDATE_DATA_SUCCESS);
        }else{
            return ResponseBean.failure(ResultCode.UPDATE_DATA_FAILURE);
        }

    }

}
